<?php
class UPLOAD{
	var $compressedData = array(); 
	var $centralDirectory = array(); // central directory   
	var $endOfCentralDirectory = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
	var $oldOffset = 0;
	var $sitePath = "";
	/**
	 * Function to create the directory where the file(s) will be unzipped
	 *
	 * @param $directoryName string 
	 *
	 */
	function __construct(){
		global $sitePath;
		$this->sitePath = $sitePath;
	}
	function GetRootPath(){
		$real_path = realpath( './' ) ;
	
		$self_path = $_SERVER['PHP_SELF'] ;
		$self_path = substr( $self_path, 0, strrpos( $self_path, '/' ) ) ;
	
		return substr( $real_path, 0, strlen( $real_path ) - strlen( $self_path ) ).$this->sitePath ;
	}	
	function addDirectory($directoryName) {
		$directoryName = str_replace("\\", "/", $directoryName);  

		$feedArrayRow = "\x50\x4b\x03\x04";
		$feedArrayRow .= "\x0a\x00";    
		$feedArrayRow .= "\x00\x00";    
		$feedArrayRow .= "\x00\x00";    
		$feedArrayRow .= "\x00\x00\x00\x00"; 

		$feedArrayRow .= pack("V",0); 
		$feedArrayRow .= pack("V",0); 
		$feedArrayRow .= pack("V",0); 
		$feedArrayRow .= pack("v", strlen($directoryName) ); 
		$feedArrayRow .= pack("v", 0 ); 
		$feedArrayRow .= $directoryName;  

		$feedArrayRow .= pack("V",0); 
		$feedArrayRow .= pack("V",0); 
		$feedArrayRow .= pack("V",0); 

		$this -> compressedData[] = $feedArrayRow;
		
		$newOffset = strlen(implode("", $this->compressedData));

		$addCentralRecord = "\x50\x4b\x01\x02";
		$addCentralRecord .="\x00\x00";    
		$addCentralRecord .="\x0a\x00";    
		$addCentralRecord .="\x00\x00";    
		$addCentralRecord .="\x00\x00";    
		$addCentralRecord .="\x00\x00\x00\x00"; 
		$addCentralRecord .= pack("V",0); 
		$addCentralRecord .= pack("V",0); 
		$addCentralRecord .= pack("V",0); 
		$addCentralRecord .= pack("v", strlen($directoryName) ); 
		$addCentralRecord .= pack("v", 0 ); 
		$addCentralRecord .= pack("v", 0 ); 
		$addCentralRecord .= pack("v", 0 ); 
		$addCentralRecord .= pack("v", 0 ); 
		$ext = "\x00\x00\x10\x00";
		$ext = "\xff\xff\xff\xff";  
		$addCentralRecord .= pack("V", 16 ); 

		$addCentralRecord .= pack("V", $this -> oldOffset ); 
		$this -> oldOffset = $newOffset;

		$addCentralRecord .= $directoryName;  

		$this -> centralDirectory[] = $addCentralRecord;  
	}	 
	
	/**
	 * Function to add file(s) to the specified directory in the archive 
	 *
	 * @param $directoryName string 
	 *
	 */
	
	function addFile($data, $directoryName)   {
 
		$directoryName = str_replace("\\", "/", $directoryName);  
	
		$feedArrayRow = "\x50\x4b\x03\x04";
		$feedArrayRow .= "\x14\x00";    
		$feedArrayRow .= "\x00\x00";    
		$feedArrayRow .= "\x08\x00";    
		$feedArrayRow .= "\x00\x00\x00\x00"; 

		$uncompressedLength = strlen($data);  
		$compression = crc32($data);  
		$gzCompressedData = gzcompress($data);  
		$gzCompressedData = substr( substr($gzCompressedData, 0, strlen($gzCompressedData) - 4), 2); 
		$compressedLength = strlen($gzCompressedData);  
		$feedArrayRow .= pack("V",$compression); 
		$feedArrayRow .= pack("V",$compressedLength); 
		$feedArrayRow .= pack("V",$uncompressedLength); 
		$feedArrayRow .= pack("v", strlen($directoryName) ); 
		$feedArrayRow .= pack("v", 0 ); 
		$feedArrayRow .= $directoryName;  

		$feedArrayRow .= $gzCompressedData;  

		$feedArrayRow .= pack("V",$compression); 
		$feedArrayRow .= pack("V",$compressedLength); 
		$feedArrayRow .= pack("V",$uncompressedLength); 

		$this -> compressedData[] = $feedArrayRow;

		$newOffset = strlen(implode("", $this->compressedData));

		$addCentralRecord = "\x50\x4b\x01\x02";
		$addCentralRecord .="\x00\x00";    
		$addCentralRecord .="\x14\x00";    
		$addCentralRecord .="\x00\x00";    
		$addCentralRecord .="\x08\x00";    
		$addCentralRecord .="\x00\x00\x00\x00"; 
		$addCentralRecord .= pack("V",$compression); 
		$addCentralRecord .= pack("V",$compressedLength); 
		$addCentralRecord .= pack("V",$uncompressedLength); 
		$addCentralRecord .= pack("v", strlen($directoryName) ); 
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("v", 0 );
		$addCentralRecord .= pack("V", 32 ); 

		$addCentralRecord .= pack("V", $this -> oldOffset ); 
		$this -> oldOffset = $newOffset;

		$addCentralRecord .= $directoryName;  


		$this -> centralDirectory[] = $addCentralRecord;  
	}

	/**
	 * Fucntion to return the zip file
	 *
	 * @return zipfile (archive)
	 */

	function getZippedfile() { 

		$data = implode("", $this -> compressedData);  
		$controlDirectory = implode("", $this -> centralDirectory);  

		return   
			$data.  
			$controlDirectory.  
			$this -> endOfCentralDirectory.  
			pack("v", sizeof($this -> centralDirectory)).     
			pack("v", sizeof($this -> centralDirectory)).     
			pack("V", strlen($controlDirectory)).             
			pack("V", strlen($data)).                
			"\x00\x00";                             
	}

	/**
	 *
	 * Function to force the download of the archive as soon as it is created
	 *
	 * @param archiveName string - name of the created archive file
	 */

	function forceDownload($archiveName) {
		$headerInfo = '';
		 
		if(ini_get('zlib.output_compression')) {
			ini_set('zlib.output_compression', 'Off');
		}

		// Security checks
		if( $archiveName == "" ) {
			echo "<html><title>Public Photo Directory - Download </title><body><BR><B>ERROR:</B> The download file was NOT SPECIFIED.</body></html>";
			exit;
		} 
		elseif ( ! file_exists( $archiveName ) ) {
			echo "<html><title>Public Photo Directory - Download </title><body><BR><B>ERROR:</B> File not found.</body></html>";
			exit;
		}

		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private",false);
		header("Content-Type: application/zip");
		header("Content-Disposition: attachment; filename=".basename($archiveName).";" );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($archiveName));
		readfile("$archiveName");
		
	}
	function DeleteFile($file_name){
		$src_path = $this->GetRootPath().$file_name;
		if (file_exists($src_path)) { 
			$deleted = @unlink($src_path);
		}
		return $deleted;
	}
	function RemoveExt($filename){
		return substr( $filename, 0, strrpos( $filename, '.' ) ) ;
	}
	function GetFileExt($File){
		$FileExt = strtolower( substr( $_FILES[$File]['name'], ( strrpos($_FILES[$File]['name'], '.') + 1 ) ) ) ;
		return $FileExt;
	}
	function UploadFile($Path, $File="", $OldFile=""){
		global $config;
		$unique = rand(0, 99).time();

		$config['Enabled'] = true ;
		$config['UserFilesPath'] = $Path ;
		
		$config['AllowedExtensions']['File']	= array() ;
		$config['DeniedExtensions']['File']		= array('php','php3','php5','phtml','asp','aspx','ascx','jsp','cfm','cfc','pl','bat','exe','dll','reg','cgi') ;
		
		$config['AllowedExtensions']['Image']	= array('jpg','gif','jpeg','png') ;
		$config['DeniedExtensions']['Image']	= array() ;
		
		$config['AllowedExtensions']['Flash']	= array('swf','fla') ;
		$config['DeniedExtensions']['Flash']	= array() ;
		
		$oFile = $_FILES[$File] ;	
			
		$sFileName = $unique.$oFile['name'] ;
		$sOriginalFileName = $sFileName ;
		
		$sExtension = $this->GetFileExt($File);
		
		$sType = 'Image' ;
		
		$arAllowed	= $config['AllowedExtensions'][$sType] ;
		$arDenied	= $config['DeniedExtensions'][$sType] ;
		
		if ( ( count($arAllowed) > 0 && !in_array( $sExtension, $arAllowed ) ) || ( count($arDenied) > 0 && in_array( $sExtension, $arDenied ) ) ){
			$UploadedFile = $OldFile;	
		}
		
		if($File!="" &&  isset( $_FILES[$File] ) && !is_null( $_FILES[$File]['tmp_name'] ) && $_FILES[$File]['name'] != ''){		
			if($OldFile){
				$DelOldFile = $Path.$OldFile;
				$Deleted = $this->DeleteFile($DelOldFile);
			}
			$sServerDir = $this->GetRootPath().$config["UserFilesPath"];
			while(true){
				$sFilePath = $sServerDir . $sFileName ;
				if ( is_file( $sFilePath ) ){
					$sFileName = $this->RemoveExt( $sOriginalFileName ) . '(' . $iCounter . ').' . $sExtension ;
				}else{
					move_uploaded_file( $_FILES[$File]['tmp_name'], $sFilePath ) ;
					if (is_file($sFilePath) ){
						$oldumask = umask(0) ;
						chmod( $sFilePath, 0777 ) ;
						umask( $oldumask ) ;
					}
					$UploadedFile = $sFileName ;
					break ;
				}
			}
		}else{
			$UploadedFile = $OldFile;	
		}
		return $UploadedFile;
	}	
	function resizeimage($imgfile, $thumbpath, $thumbsize, $filetype){
		list($width, $height) = @getimagesize($imgfile);
		@$imgratio = $width/$height;
		if($imgratio>1){
			$newwidth = $thumbsize;
			$newheight = $thumbsize/$imgratio;
		}else{
			$newheight = $thumbsize;
			$newwidth = $thumbsize*$imgratio;
		}
		$thumb = @imagecreatetruecolor($newwidth,$newheight);
		$filetype = strtolower($filetype);
                
		if($filetype == 'jpeg' || $filetype == 'jpg'){
			$source = imagecreatefromjpeg($imgfile);
			imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
			return	imagejpeg($thumb,$thumbpath,100);
		}elseif($filetype == 'png'){
                    $thumb = imagecreatetruecolor($newwidth,$newheight);
                    imagealphablending($thumb, false);
                    imagesavealpha($thumb,true);
                    $transparent = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
                    imagefilledrectangle($thumb, 0, 0, $imgSize_new, $imgSize_new, $transparent);

                    $source = imagecreatefrompng($imgfile);

                    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                    return  imagepng($thumb,$thumbpath,9);
			
		}elseif($filetype == 'gif'){
			$source = imagecreatefromgif($imgfile);
			imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
                        
			return	imagegif($thumb,$thumbpath,100);
		}
	}	
	function CompressIt($path, $file, $type){
		$sfile = $this->GetRootPath().$path.$file;
		$fileContents = file_get_contents($sfile);  
		$this->addFile($fileContents, "{$file}");  
		//--
		$fileName = $sfile.'.'.$type;
		//--
		$fd = fopen ($fileName, "wb");
		$out = fwrite ($fd, $this->getZippedfile());
		//--
		fclose ($fd);			
		//--
	}
	//-----------------	FUNCTION FOR UPLOADING FILE
	//--
	//--- $path				: is the root path file will be uploaded to.
	//--- $file 			: is the chosen file.
	//--- $compress			: 'zip', or 'rar'. The uploaded file will be compressed to 'zip', or 'rar' format. Leave it blank if unnecessary.
	//--- $delete			: If 'on', it will delete the uploaded file after compressing. 'on' chosen as recommended.
	//--- $sizelimit		: the numeric value in byte that will limit the size uploading file. Leave it blank if unnecessary.
	//-----------------
	function doUploadFile($path, $file, $compress, $delete, $sizelimit){
		$uploaded_file = $this->UploadFile($path, $file);
		if($compress == 'zip' || $compress == 'rar'){
			$this->CompressIt($path, $uploaded_file, $compress);
			if(strtolower($delete) == 'on'){
				$file_name = $path.$uploaded_file;
				$this->DeleteFile($file_name);
			}			
		}
		return $uploaded_file.'.'.$compress;	
	}
	//-----------------	FUNCTION FOR UPLOADING IMAGE
	//--
	//--- $path				: is the root path image will be uploaded to.
	//--- $file 			: is the chosen image.
	//--- $sizelimit		: the numeric value in byte that will limit the size uploading image. Leave it blank if unnecessary.
	//--- $thumbsize		: the numeric value in pixel that will resize down the uploading image. Leave it blank if unnecessary.
	//--- $delete			: If 'on' and $thumbsize has a valid value, it will delete the large image after resizing.
	//-----------------
	function doUploadImage($path, $file, $sizelimit, $thumbsize, $delete){
		$uploaded_img = $this->UploadFile($path, $file);
		if($thumbsize != ''){
			$imgfile = $this->GetRootPath().$path.$uploaded_img;
			@$img_size = @getimagesize($imgfile);
			$width = $img_size[0];
			if($width > $thumbsize){
				$resize_to = $thumbsize;
			}else{
				$resize_to = $width;
			}
			$thumbpath = $this->GetRootPath().$path.'thumb'.$uploaded_img;
			$filetype = $this->GetFileExt($file);
			$this->resizeimage($imgfile, $thumbpath, $resize_to, $filetype);				
			//--
			if(strtolower($delete) == 'on'){
				$file_name = $path.$uploaded_img;
				$this->DeleteFile($file_name);
			}			
		}
		return $uploaded_img;
	}
        function UploadAllFile($Path, $File="", $OldFile=""){
		global $config;
		$unique = rand(0, 99).time();

		
		
		$oFile = $_FILES[$File] ;	
			
		$sFileName = $unique.$oFile['name'] ;
                
		$sOriginalFileName = $sFileName ;
		
		$sExtension = $this->GetFileExt($File);
		
		$sType = 'Image' ;
		
		
		if($File!="" &&  isset( $_FILES[$File] ) && !is_null( $_FILES[$File]['tmp_name'] ) && $_FILES[$File]['name'] != ''){		
			if($OldFile){
				$DelOldFile = $Path.$OldFile;
				$Deleted = $this->DeleteFile($DelOldFile);
			}
			$sServerDir = $this->GetRootPath().$config["UserFilesPath"];
			while(true){
				$sFilePath = $sServerDir. $Path . $sFileName ;
				if ( is_file( $sFilePath ) ){
					$sFileName = $this->RemoveExt( $sOriginalFileName ) . '(' . $iCounter . ').' . $sExtension ;
				}else{
                                    
					move_uploaded_file( $_FILES[$File]['tmp_name'], $sFilePath ) ;
					if (is_file($sFilePath) ){
						$oldumask = umask(0) ;
						chmod( $sFilePath, 0777 ) ;
						umask( $oldumask ) ;
					}
					$UploadedFile = $sFileName ;
					break ;
				}
			}
		}else{
			$UploadedFile = $OldFile;	
		}
                
		return $UploadedFile;
	}
}
?>